package com.wc.AlgoOJ.GR0102;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * @Author congege
 * @Description
 * @Date Created in 2023/12/22-16:21
 */
public class Main2 {
    static int maxN = 1000 + 10;
    static int[][] steps = new int[maxN][maxN];
    static char[][] map = new char[maxN][];
    static int n, m;
    static int startX, startY;
    static int endX, endY;
    static int ans = -1;
    static int[] positionX = new int[]{-1, 0, 1, 0};
    static int[] positionY = new int[]{0, 1, 0, -1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String s = sc.next();
            int st = s.indexOf('S');
            int et = s.indexOf('E');
            if (st != -1) {
                startX = i;
                startY = st;
            }
            if (et != -1) {
                endX = i;
                endY = et;
            }
            map[i] = s.toCharArray();
        }
        for (int i = 0; i < n; i++) {
            Arrays.fill(steps[i], 0, m, maxN * maxN);
        }
        steps[startX][startY] = 0;
        bfs();
        System.out.println(ans);
    }

    public static void bfs() {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(startX);
        queue.add(startY);
        int x, y, step;
        while (!queue.isEmpty()) {
            x = queue.poll();
            y = queue.poll();
            if (x == endX && y == endY) {
                ans = steps[x][y];
                break;
            }
            step = steps[x][y];
            for (int i = 0; i < 4; i++) {
                int nextX = x + positionX[i];
                int nextY = y + positionY[i];
                if (!isBorder(nextX, nextY) && (map[nextX][nextY] == '.' || map[nextX][nextY] == 'E') && step + 1 < steps[nextX][nextY]) {
                    steps[nextX][nextY] = step + 1;
                    queue.add(nextX);
                    queue.add(nextY);
                }
            }
        }
    }

    public static boolean isBorder(int x, int y) {
        return x < 0 || x == n || y < 0 || y == m;
    }
}

